package com.oocl.ha.merchant.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

public class UploadImgUtil {

	public static String uploadImg(MultipartFile file) {
		System.out.println(file.getOriginalFilename());
		UUID uuid = UUID.randomUUID();
		String imgName = uuid.toString() + "_" + file.getOriginalFilename();
		FileOutputStream os;
		try {
			System.out.println(file.getBytes().length);
			os = new FileOutputStream(ConfigUtil.getConfigValue("merchant.properties", "localImgPath") + imgName);
			FileInputStream in = (FileInputStream) file.getInputStream();
			int b = 0;
			while ((b = in.read()) != -1) {
				os.write(b);
			}
			os.flush();
			os.close();
			in.close();
			return imgName;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static OutputStream showImage(String fname,HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		response.setContentType("image/png");
		String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
		String rootPath = "D:/temp_image/";
		String absolutePath = rootPath + newpath;
		FileInputStream fis = new FileInputStream(absolutePath);
		OutputStream os = response.getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			// os.flush();
			return os;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
		return null;
	}

}
